<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>{{ i18n('business.supplier.from') }}</div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button icon="Back" @click="router.go(-1)">
              {{ i18n('common.return') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="admin_form_main">
        <el-form label-width="130px" ref="formRef" :model="dataForm" :rules="dataRule">
          <el-card class="box-card" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('common.basic_info') }}</span>
              </div>
            </template>
            <div class="text item text-center">
              <el-row>
                <el-col :span="4">
                  <el-form-item :label="i18n('organization.logo')" prop="logo">
                    <el-upload
                      class="avatar-uploader"
                      :action="$http.adornUrl('/file/picture')"
                      :show-file-list="false"
                      :headers="upload_headers"
                      :on-success="handlePictureSuccess"
                      :before-upload="beforePictureUpload">
                      <img v-if="dataForm.logo" :src="dataForm.logo" class="avatar-upload"/>
                      <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
                    </el-upload>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.detail.license')" prop="license">
                    <el-upload
                      class="avatar-uploader"
                      :action="$http.adornUrl('/file/picture')"
                      :show-file-list="false"
                      :headers="upload_headers"
                      :on-success="handleLicenseSuccess"
                      :before-upload="beforePictureUpload">
                      <img v-if="dataForm.license" :src="dataForm.license" class="avatar-upload"/>
                      <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-form-item :label="i18n('business.supplier.type')" prop="type">
                    <el-select
                      v-model="dataForm.type"
                      :placeholder="i18n('common.please_select') + i18n('business.supplier.type')" filterable clearable>
                      <el-option v-for="(v, k) in typeList" :label="v.text" :key="k" :value="v.value"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.chinese_title')">
                    <el-input v-model="dataForm.chinese_title" :placeholder="i18n('common.please_input') + i18n('organization.chinese_title')" show-word-limit maxlength="50" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.english_title')">
                    <el-input v-model="dataForm.english_title" :placeholder="i18n('common.please_input') + i18n('organization.english_title')" show-word-limit maxlength="100" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.tax_code')" prop="tax_code">
                    <el-input v-model="dataForm.tax_code" :placeholder="i18n('common.please_input') + i18n('organization.tax_code')" show-word-limit maxlength="32" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.business_scope')" prop="business_scope">
                    <el-input
                      type="textarea"
                      v-model="dataForm.business_scope"
                      :rows="3"
                      show-word-limit
                      maxlength="300"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.business_scope')">
                    </el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.country_id')" prop="country_id">
                    <el-select
                      v-model="dataForm.country_id"
                      @change="setAreaStatus"
                      :placeholder="i18n('common.please_select') + i18n('business.supplier.country_id')" filterable clearable>
                      <el-option v-for="(v, k) in countryList" :label="v.text" :key="k" :value="v.value"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.area')" v-if="areaStatus">
                    <el-cascader v-model="dataForm.area" :placeholder="$t('common.please_select') + $t('business.supplier.area')" :options="areaList" :props="levelProps" clearable></el-cascader>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.detail.address')" prop="address">
                    <el-input
                      type="textarea"
                      v-model="dataForm.address"
                      :rows="3"
                      show-word-limit
                      maxlength="500"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.address')">
                    </el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.manager_name')" prop="manager_name">
                    <el-input
                      v-model="dataForm.manager_name"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.manager_name')" show-word-limit maxlength="12" clearable></el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.manager_mobile')" prop="manager_mobile">
                    <el-input
                      v-model="dataForm.manager_mobile"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.manager_mobile')" show-word-limit maxlength="15" clearable></el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.start_time')" prop="start_time">
                    <el-date-picker v-model="dataForm.start_time" type="date" :placeholder="i18n('common.please_input') + i18n('business.supplier.start_time')" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.end_time')" prop="end_time">
                    <el-date-picker v-model="dataForm.end_time" type="date" :disabled-date="disabledDate" :placeholder="i18n('common.please_input') + i18n('business.supplier.end_time')" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.harbor_code')" prop="harbor_code">
                    <el-select v-model="dataForm.harbor_code" :placeholder="i18n('common.please_select') + i18n('business.supplier.harbor_code')" :remote-method="loadHarborList" :loading="loading" reserve-keyword filterable remote multiple clearable>
                      <el-option v-for="(v, k) in harborList" :label="v.chinese_name" :key="k" :value="v.code">
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.label_id')" prop="label_id">
                    <el-select
                      v-model="dataForm.label_id"
                      :placeholder="i18n('common.please_select') + i18n('business.supplier.label_id')" filterable multiple collapse-tags clearable>
                      <el-option v-for="(v, k) in labelList" :label="v.title" :key="k" :value="v.id"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('common.sort')" prop="sort">
                    <el-input-number v-model="dataForm.sort" :min="0">
                    </el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('common.detail_info') }}</span>
              </div>
            </template>
            <div class="text item">
              <el-descriptions border :column="3">
                <el-descriptions-item width="200" :label="i18n('business.supplier.detail.mode')" :span="3" label-align="right">
                  {{ dataForm.mode }}
                </el-descriptions-item>
                <el-descriptions-item width="200" :label="i18n('business.supplier.detail.website')" label-align="right">
                  {{ dataForm.website }}
                </el-descriptions-item>
                <el-descriptions-item width="200" :label="i18n('business.supplier.detail.mobile')" label-align="right">
                  {{ dataForm.mobile }}
                </el-descriptions-item>
                <el-descriptions-item width="200" :label="i18n('business.supplier.detail.email')" label-align="right">
                  {{ dataForm.email }}
                </el-descriptions-item>
                <el-descriptions-item width="200" :label="i18n('business.supplier.detail.description')" :span="3" label-align="right">
                  {{ dataForm.description }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('business.supplier.resource') }}</span>
              </div>
            </template>
            <div class="text item">
              <el-form-item :label="i18n('business.supplier.banner.url')">
                <el-link class="mr10" v-if="dataForm.banner" v-for="(v, k) in dataForm.banner" :key="k" :href="v.url" :underline="false" target="_blank">
                  <el-image class="cx-list-image" :src="v.url">
                    <template v-slot:error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </el-link>
              </el-form-item>

              <el-form-item :label="i18n('business.supplier.environment.url')">
                <el-link class="mr10" v-if="dataForm.environment" v-for="(v, k) in dataForm.environment" :key="k" :href="v.url" :underline="false" target="_blank">
                    <el-image class="cx-list-image" :src="v.url">
                      <template v-slot:error>
                        <div class="image-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </el-link>
              </el-form-item>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('business.supplier.contact.info') }}</span>
              </div>
            </template>
            <div class="text item">
              <el-table :data="dataForm.contact" stripe>
                <el-table-column prop="name" :label="i18n('business.supplier.contact.name')" min-width="240">
                </el-table-column>

                <el-table-column prop="position" :label="i18n('business.supplier.contact.position')" width="100">
                </el-table-column>

                <el-table-column prop="mobile" :label="i18n('business.supplier.contact.mobile')" min-width="180">
                </el-table-column>

                <el-table-column prop="email" :label="i18n('business.supplier.contact.email')" min-width="180">
                </el-table-column>

                <el-table-column :label="i18n('business.supplier.contact.url')" width="120">
                  <template v-slot="scope">
                    <el-link class="mr10" v-if="scope.row.url" :href="scope.row.url" :underline="false" target="_blank">
                      <el-image class="cx-list-image" :src="scope.row.url">
                        <template v-slot:error>
                          <div class="image-slot">
                            <el-icon><Picture /></el-icon>
                          </div>
                        </template>
                      </el-image>
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('business.supplier.business.info') }}</span>
              </div>
            </template>
            <div class="text item">
              <el-table :data="dataForm.business" stripe>
                <el-table-column :label="i18n('business.supplier.business.type')" width="120">
                  <template v-slot="scope">
                    {{ scope.row.business.chinese_title }}
                  </template>
                </el-table-column>

                <el-table-column prop="description" :label="i18n('business.supplier.business.description')" min-width="200">
                </el-table-column>

                <el-table-column :label="i18n('business.supplier.business.case.url')" min-width="120">
                  <template v-slot="scope">
                    <el-link class="mr10" v-if="scope.row.case" v-for="(v, k) in scope.row.case" :key="k" :href="v.url" :underline="false" target="_blank">
                      <el-image class="cx-list-image" :src="v.url">
                        <template v-slot:error>
                          <div class="image-slot">
                            <el-icon><Picture /></el-icon>
                          </div>
                        </template>
                      </el-image>
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <div class="text item">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="dataFormSubmit(formRef)">
                  {{ i18n('common.confirm') }}
                </el-button>
                <el-button @click="resetForm(formRef)">
                  {{ i18n('common.reset') }}
                </el-button>
              </el-form-item>
            </div>
          </el-card>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="business-supplier-form">
  import { useBase } from "@/hooks/base/useBase"
  import { useForm } from "@/hooks/form/useForm"
  import { useUpload } from "@/hooks/upload/useUpload"

  const { router, query, i18n, isAuth } = useBase()

  const model = ref('business/supplier')

  const current_time = ref('')

  const loading = ref(false)
  const areaStatus = ref(true)

  const typeList = ref([])
  const harborList = ref([])
  const labelList = ref([])
  const countryList = ref([])
  const areaList = ref([])

  const modeList = ref([
    {id: 1, title: '模式一',},
    {id: 2, title: '模式二',}
  ])

  const levelProps = ref({
    label: 'title',
    value: 'id',
    children: 'children',
    checkStrictly: false
  })

  const dataForm = reactive({
    id: 0,
    organization_id: 0,
    logo: '',
    tax_code: '',
    chinese_title: '',
    english_title: '',
    type: '1',
    business_scope: '',
    license: '',
    manager_name: '',
    manager_mobile: '',
    country_id: '1',
    area: '',
    mode: '',
    description: '',
    website: '',
    mobile: '',
    email: '',
    address: '',
    start_time: '',
    end_time: '',
    sort: 0,
    harbor_code: [],
    label_id: [],
    banner: [],
    environment: [],
    business: [],
    contact: [],
  })

  const dataRule = reactive({
    manager_name: [{
      required: true,
      message: i18n('business.supplier.rules.manager_name.require'),
      trigger: 'blur'
    }],
    manager_mobile: [{
      required: true,
      message: i18n('business.supplier.rules.manager_mobile.require'),
      trigger: 'blur'
    }],
  })

  const {
    formRef,
    resetForm
  } = useForm(model.value, dataForm)

  const {
    upload_headers,
    beforePictureUpload,
  } = useUpload(dataForm, '')

  const init = (form) => {
    dataForm.id = query.id || 0

    nextTick(() => {
      form.value.resetFields()
      if (dataForm.id) {
        $http({
          url: $http.adornUrl(`/${model.value}/view/${dataForm.id}`),
          method: 'get',
          params: $http.adornParams({}),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            dataForm.id = data.data.id
            dataForm.organization_id = data.data.organization_id
            dataForm.country_id = data.data.country_id + ''
            dataForm.type = data.data.type.value
            dataForm.business_scope = data.data.business_scope
            dataForm.manager_name = data.data.manager_name
            dataForm.manager_mobile = data.data.manager_mobile
            dataForm.start_time = data.data.start_time
            dataForm.end_time = data.data.end_time
            dataForm.sort = data.data.sort
            dataForm.area = data.data.area

            if(2 == dataForm.country_id)
            {
              areaStatus.value = false
            }
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/organization/data`),
              method: 'get',
              params: $http.adornParams({
                'id': dataForm.organization_id
              }),
            }).then(({ data }) => {
              if (data.data && data.status === 200) {
                dataForm.tax_code = data.data.tax_code
                dataForm.logo = data.data.logo
                dataForm.chinese_title = data.data.chinese_title
                dataForm.english_title = data.data.english_title

                if(data.data.detail) {
                  dataForm.license = data.data.detail.license
                }
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/detail/data`),
              method: 'get',
              params: $http.adornParams({
                'supplier_id': dataForm.id
              }),
            }).then(({ data }) => {
              if (data.data && data.status === 200) {
                dataForm.mode = data.data.mode
                dataForm.description = data.data.description
                dataForm.website = data.data.website
                dataForm.mobile = data.data.mobile
                dataForm.email = data.data.email
                dataForm.address = data.data.address
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/harbor/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                data.data.forEach((res) => {
                  dataForm.harbor_code.push(res.harbor_code)
                })
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/label/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                data.data.forEach((res) => {
                  dataForm.label_id.push(res.label_id)
                })
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/contact/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                dataForm.contact = data.data
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/business/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                dataForm.business = data.data
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/resource/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id,
                type: 1
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                dataForm.banner = data.data
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/resource/select`),
              method: 'get',
              params: $http.adornParams({
                supplier_id: dataForm.id,
                type: 2
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                dataForm.environment = data.data
              }
            })
          }
        })
      }
    })
  }

  // 表单提交
  const dataFormSubmit = (form) => {
    form.validate(async (valid, fields) => {
      if (valid) {
        $http({
          url: $http.adornUrl(`/${model.value}/handle`),
          method: 'post',
          data: $http.adornData({
            id: dataForm.id || undefined,
            organization_id: dataForm.organization_id,
            tax_code: dataForm.tax_code,
            logo: dataForm.logo,
            chinese_title: dataForm.chinese_title,
            english_title: dataForm.english_title,
            business_scope: dataForm.business_scope,
            type: dataForm.type,
            license: dataForm.license,
            manager_name: dataForm.manager_name,
            manager_mobile: dataForm.manager_mobile,
            country_id: dataForm.country_id,
            area: dataForm.area,
            start_time: dataForm.start_time,
            end_time: dataForm.end_time,
            sort: dataForm.sort,
            harbor_code: dataForm.harbor_code,
            label_id: dataForm.label_id,
            mode: dataForm.mode,
            description: dataForm.description,
            website: dataForm.website,
            mobile: dataForm.mobile,
            email: dataForm.email,
            address: dataForm.address,
          }),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            $message.success(i18n('common.handle_success'))
            router.go(-1)
          } else {
            $message.error(data.message)
          }
        })
      }
    })
  }

  const loadTypeList = () => {
    $http({
      url: $http.adornUrl('/dictionary/data'),
      method: 'get',
      params: $http.adornParams({
        title: 'supplier_type',
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        typeList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadCountryList = () => {
    $http({
      url: $http.adornUrl('/dictionary/data'),
      method: 'get',
      params: $http.adornParams({
        title: 'country_type',
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        countryList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadAreaList = () => {
    $http({
      url: $http.adornUrl('/common/area/three'),
      method: 'get',
      params: $http.adornParams({}),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        areaList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadHarborList = (keyword) => {
    if (keyword && keyword.length > 1) {
      loading.value = true
      $http({
        url: $http.adornUrl('/business/harbor/select'),
        method: 'get',
        params: $http.adornParams({
          keyword: keyword
        }),
      }).then(({ data }) => {
        if (data && data.status === 200) {
          harborList.value = data.data
          loading.value = false
        } else {
          $message.error(data.message)
        }
      })
    } else {
      harborList.value = []
      loading.value = false
    }
  }

  const loadLabelList = () => {
    $http({
      url: $http.adornUrl('/business/label/supplier/select'),
      method: 'get',
      params: $http.adornParams({}),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        labelList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const setAreaStatus = (country_id) => {
    if(1 == country_id) {
      areaStatus.value = true
    } else {
      areaStatus.value = false
    }
  }

  /**
   * 公司logo上传成功函数
   *
   * @param {[type]} res 上传结果
   * @param {[type]} file 上传文件
   * @return {[type]}
   */
  const handlePictureSuccess = (res, file) => {
    dataForm.logo = res.data
  }


  /**
   * 营业执照上传成功函数
   *
   * @param {[type]} res 上传结果
   * @param {[type]} file 上传文件
   * @return {[type]}
   */
  const handleLicenseSuccess = (res, file) => {
    dataForm.license = res.data
  }

  const disabledDate = (time) => {
    return time.getTime() - 24 * 60 * 60 * 1000 * 30 < current_time.value
  }

  onMounted(() => {
    current_time.value = Date.now()

    init(formRef)

    loadTypeList()
    loadCountryList()
    loadAreaList()
    loadLabelList()
  })
</script>

<style lang="scss" scoped>
  .cx-list-image {
    width: 30px;
    height: 30px;
  }
</style>
